class AuthProvider:
    def __init__(self, get_user, auth_key='user_id'):
        self.get_user = get_user
        self.auth_key = auth_key

    def authenticate(self, view):
        user_id = view.session.get(self.auth_key)
        if user_id:
            try:
                return self.get_user(user_id)
            except Exception:
                pass

    def login(self, view, user):
        view._user = user
        session = view.session
        if self.auth_key in session:
            if session[self.auth_key] != user.id:
                # To avoid reusing another user's session, create a new, empty
                # session if the existing session corresponds to a different
                # authenticated user.
                session.flush()
        else:
            session.cycle_session_id()
        session[self.auth_key] = user.id

        # cookie is set by SessionFilter
        #user_logged_in.send(sender=user.__class__, request=request, user=user)

    def logout(self, view):
        """
        Removes the authenticated user's ID from the request and flushes their
        session data.
        """
        # Dispatch the signal before the user is logged out so the receivers have a
        # chance to find out *who* logged out.
        #user_logged_out.send(sender=user.__class__, request=request, user=user)

        view.session.flush()
